/**
 * AI前端项目生成系统页面
 * 允许用户配置并生成一个全新的前端项目。
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Card, Typography, Spin, message, Steps, Button } from 'antd';
import { AppDispatch } from '@/store';
import { RootState } from '@/types';
import { BaseComponent } from '@/types/project';
import { 
  fetchProjectTypes, 
  fetchUIFrameworks, 
  fetchBaseComponents,
  analyzeRequirements,
  setConfigField,
  // saveProjectConfig
} from '@/store/slices/projectSlice';

// 步骤组件导入
import {
  BasicConfigStep,
  TechStackStep, 
  ComponentsSelectionStep,
  ProjectArchitectureStep,
  ComponentGenerationStep,
  AdvancedSettingsStep,
  StepNavigation,
  StatusAlerts
} from '@/components/ProjectConfig';

const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;

// API 基础地址（优先环境变量，其次相对路径）
const API_BASE = import.meta.env.VITE_API_BASE_URL || '/api/v1';

const getRequiredBaseComponentNames = (components: BaseComponent[]): string[] => {
  const explicit = components.filter(component => component.required).map(component => component.name);
  if (explicit.length > 0) {
    return explicit;
  }
  return components.slice(0, 2).map(component => component.name);
};

const ProjectConfig: React.FC = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch<AppDispatch>();

  // 用于API调用的加载状态
  const [apiLoading, setApiLoading] = useState(false);
  const [generatedProjectPath, setGeneratedProjectPath] = useState<string | null>(null);
  const [downloadLoading, setDownloadLoading] = useState(false);
  
  // 步骤控制状态
  const [currentStep, setCurrentStep] = useState(0);
  
  // 步骤定义
  const steps = [
    {
      title: '核心配置',
      description: '基本项目信息',
    },
    {
      title: '技术栈配置',
      description: '平台和框架选择',
    },
    {
      title: '组件选择',
      description: '基础组件和扩展组件',
    },
    {
      title: '项目架构',
      description: '状态管理、路由、布局配置',
    },
    {
      title: '组件生成',
      description: '可选功能组件（如登录/菜单）',
    },
    {
      title: '高级设置',
      description: '菜单层级和自定义需求',
    },
  ];

  // 从 Redux store 中获取用于表单填充的状态
  const { config, projectTypes, uiFrameworks, baseComponents, directoryStructure, directorySummary, loading: reduxLoading, error, isConfigured } = useSelector(
    (state: RootState) => state.project
  );

  const statusAlerts = useMemo(() => {
    const alerts = [];
    if (error) {
      alerts.push({
        key: 'error',
        type: 'error' as const,
        message: '数据加载错误',
        description: error,
      });
    }
    if (isConfigured) {
      alerts.push({
        key: 'config-loaded',
        type: 'info' as const,
        message: '配置已加载',
        description: '已从缓存加载您上次的配置。您可以直接修改或生成项目。',
      });
    }
    return alerts;
  }, [error, isConfigured]);

  useEffect(() => {
    // 获取项目类型和前端框架用于下拉选择
    dispatch(fetchProjectTypes());
    dispatch(fetchUIFrameworks());
    
    // 拉取系统默认值（后端统一配置必要参数与默认值）并应用到表单
    (async () => {
      try {
        const resp = await fetch(`${API_BASE}/system-settings`);
        if (resp.ok) {
          const data = await resp.json();
          const defaults = data?.defaults || {};
          // 只在表单未触碰时应用默认值，避免覆盖用户已填内容
          const current = form.getFieldsValue();
          const patch: Record<string, any> = {};
          if (!current.language && defaults.language) patch.language = defaults.language;
          if (!current.buildTool && defaults.buildTool) patch.buildTool = defaults.buildTool;
          if (!current.targetPlatform && defaults.targetPlatform) patch.targetPlatform = defaults.targetPlatform;
          if (Object.keys(patch).length) {
            form.setFieldsValue(patch);
          }
        }
      } catch (e) {
        console.warn('获取系统默认值失败：', e);
      }
    })();
  }, [dispatch]);

  useEffect(() => {
    // 当前端框架改变时，获取对应的基础组件
    if (config.uiFramework) {
      dispatch(fetchBaseComponents(config.uiFramework));
    }
  }, [config.uiFramework, dispatch]);

  // 监听表单中UI框架的变化
  const handleUIFrameworkChange = (value: string) => {
    // 更新Redux配置
    dispatch(setConfigField({ field: 'uiFramework', value }));
    // 获取对应框架的基础组件
    dispatch(fetchBaseComponents(value));
  };

  // 处理项目架构配置变化
  const handleArchitectureChange = (architecture: any) => {
    // 根据架构选择自动添加必需的组件
    const currentBaseComponents = form.getFieldValue('baseComponents') || [];
    const newRequiredComponents: string[] = [];

    // 状态管理相关组件
    if (architecture.stateManagement && architecture.stateManagement !== 'none') {
      if (architecture.stateManagement === 'redux-toolkit') {
        newRequiredComponents.push('@reduxjs/toolkit', 'react-redux');
      } else if (architecture.stateManagement === 'zustand') {
        newRequiredComponents.push('zustand');
      } else if (architecture.stateManagement === 'pinia') {
        newRequiredComponents.push('pinia');
      } else if (architecture.stateManagement === 'vuex') {
        newRequiredComponents.push('vuex');
      }
    }

    // 路由相关组件
    if (architecture.router && architecture.router !== 'none') {
      if (architecture.router === 'react-router') {
        newRequiredComponents.push('react-router-dom');
      } else if (architecture.router === 'vue-router') {
        newRequiredComponents.push('vue-router');
      }
    }

    // API工具相关组件
    if (architecture.apiTools && architecture.apiTools.length > 0) {
      if (architecture.apiTools.includes('axios')) {
        newRequiredComponents.push('axios');
      }
    }

    // 更新基础组件列表
    const updatedComponents = Array.from(new Set([...currentBaseComponents, ...newRequiredComponents]));
    form.setFieldValue('baseComponents', updatedComponents);
  };

  useEffect(() => {
    // 当配置从 Redux 加载后，设置表单的值
    if (Object.keys(config).length > 0) {
      form.setFieldsValue(config);
    }
  }, [config, form]);

  const handleNext = async () => {
    try {
      // 验证当前步骤的表单字段
      if (currentStep === 0) {
        await form.validateFields(['projectName', 'projectType']);
        
        // 第一步验证通过后，保存基本信息到 Redux
        const formValues = form.getFieldsValue();
        console.log('第一步表单值:', formValues);
        dispatch(setConfigField({ field: 'projectName', value: formValues.projectName }));
        dispatch(setConfigField({ field: 'projectType', value: formValues.projectType }));
        dispatch(setConfigField({ field: 'description', value: formValues.description }));
        
      } else if (currentStep === 1) {
        await form.validateFields(['uiFramework', 'language', 'buildTool', 'targetPlatform']);
        
        // 保存第二步的配置到 Redux
        const formValues = form.getFieldsValue();
        console.log('第二步表单值:', formValues);
        dispatch(setConfigField({ field: 'uiFramework', value: formValues.uiFramework }));
        dispatch(setConfigField({ field: 'language', value: formValues.language }));
        dispatch(setConfigField({ field: 'buildTool', value: formValues.buildTool }));
        dispatch(setConfigField({ field: 'targetPlatform', value: formValues.targetPlatform }));
        dispatch(setConfigField({ field: 'requirementDescription', value: formValues.requirementDescription }));
        
        // 从第二步跳转到第三步时，触发AI分析用户需求
        const requirementDescription = formValues.requirementDescription;
        const uiFramework = formValues.uiFramework;
        const language = formValues.language;
        const buildTool = formValues.buildTool;
        const targetPlatform = formValues.targetPlatform;
        const enableAIRecommendation = formValues.enableAIRecommendation !== false;
        
        if (enableAIRecommendation && requirementDescription) {
          try {
            // 获取当前框架的必选基础组件
            const requiredComponents = getRequiredBaseComponentNames(baseComponents);
            
            // 调用AI分析接口
            await dispatch(analyzeRequirements({ 
              description: requirementDescription,
              uiFramework: uiFramework,
              language: language,
              buildTool: buildTool,
              targetPlatform: targetPlatform,
              excludeComponents: requiredComponents
            }));
            message.success('AI需求分析完成，为您推荐了扩展组件');
          } catch {
            message.warning('AI分析失败，但您仍可手动选择组件');
          }
        }
      } else if (currentStep === 2) {
        // 第三步：组件选择，保存组件选择
        const formValues = form.getFieldsValue();
        console.log('第三步表单值:', formValues);
        dispatch(setConfigField({ field: 'baseComponents', value: formValues.baseComponents }));
        dispatch(setConfigField({ field: 'extendedComponents', value: formValues.extendedComponents }));
      } else if (currentStep === 3) {
        // 第四步：项目架构配置，保存架构配置
        const formValues = form.getFieldsValue();
        console.log('第四步表单值:', formValues);
        dispatch(setConfigField({ field: 'stateManagement', value: formValues.stateManagement }));
        dispatch(setConfigField({ field: 'router', value: formValues.router }));
        dispatch(setConfigField({ field: 'layout', value: formValues.layout }));
        dispatch(setConfigField({ field: 'devProxy', value: formValues.devProxy }));
        dispatch(setConfigField({ field: 'testProxy', value: formValues.testProxy }));
        dispatch(setConfigField({ field: 'prodProxy', value: formValues.prodProxy }));
        dispatch(setConfigField({ field: 'additionalConfig', value: formValues.additionalConfig }));
      } else if (currentStep === 4) {
        // 第五步：组件生成，保存选择
        const formValues = form.getFieldsValue();
        console.log('第五步表单值（组件生成）:', formValues);
        dispatch(setConfigField({ field: 'generatedComponents', value: formValues.generatedComponents }));
      } else if (currentStep === 5) {
        // 第六步：高级设置，保存高级配置
        const formValues = form.getFieldsValue();
        console.log('第六步表单值:', formValues);
        dispatch(setConfigField({ field: 'maxLevels', value: formValues.maxLevels }));
        dispatch(setConfigField({ field: 'customRequirements', value: formValues.customRequirements }));
      }
      // 步进前，保存当前累积配置到后端（持久化）
      const currentStepValues = form.getFieldsValue();
      const allValues = { ...config, ...currentStepValues } as any;
  // 按新方案：页面与后端方法不做配置持久化，因此此处不再写入数据库

      setCurrentStep(currentStep + 1);
    } catch (error) {
      console.error('表单验证错误:', error);
      message.error('请检查当前步骤的必填项');
    }
  };

  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleSubmit = async () => {
    try {
      // 1. 获取当前步骤的表单值（只有当前步骤的字段在DOM中）
      const currentStepValues = form.getFieldsValue();
      
      // 2. 合并 Redux 中的配置和当前表单值
      const allValues = {
        ...config,  // Redux 中保存的所有步骤的值
        ...currentStepValues,  // 当前步骤的值覆盖
      };
      
      console.log('Redux 配置:', config);
      console.log('当前步骤表单值:', currentStepValues);
      console.log('合并后的所有值:', allValues);
      
      // 3. 验证必需字段
      if (!allValues.projectName) {
        message.error('请返回第一步填写项目名称');
        return;
      }
      if (!allValues.projectType) {
        message.error('请返回第一步选择项目类型');
        return;
      }
      if (!allValues.uiFramework) {
        message.error('请返回第二步选择前端框架');
        return;
      }
      
      setApiLoading(true);
      setGeneratedProjectPath(null);
      
      // 4. 处理基础组件数据：创建新数组避免修改不可变对象
      const selectedComponents: string[] = [...(allValues.baseComponents || [])];

      getRequiredBaseComponentNames(baseComponents).forEach(name => {
        if (!selectedComponents.includes(name)) {
          selectedComponents.push(name);
        }
      });
      
      // 5. 组装自定义需求，追加“组件生成”提示（避免后端 schema 变更）
      const componentLabelMap: Record<string, string> = {
        login: '登录组件',
        menu: '菜单组件',
      };
      const selectedFeatureComponents: string[] = Array.isArray(allValues.generatedComponents)
        ? allValues.generatedComponents
        : [];
      const componentsHint = selectedFeatureComponents.length
        ? `组件生成: ${selectedFeatureComponents.map((k) => componentLabelMap[k] || k).join(', ')}`
        : '';
      const customRequirementsFinal = componentsHint
        ? (allValues.customRequirements ? `${allValues.customRequirements}\n${componentsHint}` : componentsHint)
        : (allValues.customRequirements || undefined);

      // 6. 确保所有必需字段都有值
      const requestData = {
        projectName: allValues.projectName,
        projectType: allValues.projectType,
        uiFramework: allValues.uiFramework,
        language: allValues.language || 'typescript',
        buildTool: allValues.buildTool || 'vite',
        targetPlatform: allValues.targetPlatform || 'web',
        baseComponents: selectedComponents,
        extendedComponents: allValues.extendedComponents || [],
        description: allValues.description || undefined,
        maxLevels: allValues.maxLevels || 2,
        customRequirements: customRequirementsFinal,
        requirementDescription: allValues.requirementDescription || undefined,
        stateManagement: allValues.stateManagement || undefined,
        router: allValues.router || undefined,
        layout: allValues.layout || undefined,
        devProxy: allValues.devProxy || undefined,
        testProxy: allValues.testProxy || undefined,
        prodProxy: allValues.prodProxy || undefined,
        additionalConfig: allValues.additionalConfig || undefined,
        directoryStructure: directoryStructure || [],
        directorySummary: directorySummary || undefined
      };

      console.log('提交项目配置', requestData);
      
      // 3. 调用后端 FastAPI 服务
      const response = await fetch(`${API_BASE}/generate-project`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });

      const result = await response.json();

      if (!response.ok) {
        let errorMessage = '项目生成失败，请检查后端服务日志。';
        if (result?.detail) {
          if (Array.isArray(result.detail)) {
            // Pydantic 验证错误，格式化显示
            errorMessage = 'API验证错误：\n' + result.detail
              .map((item: any) => {
                const field = item?.loc?.[1] || item?.loc?.[0] || '未知字段';
                const msg = item?.msg || '未知错误';
                const type = item?.type || '';
                return `- 字段 "${field}": ${msg} (${type})`;
              })
              .join('\n');
            console.error('详细验证错误:', result.detail);
            console.log('发送的数据:', requestData);
          } else if (typeof result.detail === 'string') {
            errorMessage = result.detail;
          } else {
            errorMessage = JSON.stringify(result.detail);
          }
        }
        throw new Error(errorMessage);
      }
      
      setGeneratedProjectPath(result.project_path || null);
      message.success(result.message || '项目生成成功！');
      
    } catch (error: any) {
      console.error('项目生成请求失败:', error);
      // 检查是表单校验错误还是API错误
      if (error.errorFields) {
        message.error('请检查表单，填写所有必填项。');
      } else {
        message.error(`请求失败: ${error.message}`);
      }
    } finally {
      setApiLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentStep(0);
    setGeneratedProjectPath(null);
  };

  const generatedProjectName = useMemo(() => {
    if (!generatedProjectPath) return null;
    const parts = generatedProjectPath.split(/[/\\]/).filter(Boolean);
    return parts.length ? parts[parts.length - 1] : null;
  }, [generatedProjectPath]);

  const handleDownloadProject = useCallback(async () => {
    if (!generatedProjectName) return;
    try {
      setDownloadLoading(true);
  const response = await fetch(`${API_BASE}/download-project/${encodeURIComponent(generatedProjectName)}`);
      if (!response.ok) {
        const text = await response.text();
        throw new Error(text || '下载失败');
      }
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${generatedProjectName}.zip`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      message.success('项目压缩包下载开始');
    } catch (error: any) {
      message.error(`下载失败: ${error?.message || '未知错误'}`);
    } finally {
      setDownloadLoading(false);
    }
  }, [generatedProjectName]);

  // 渲染不同步骤的表单内容
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return <BasicConfigStep projectTypes={projectTypes} />;
      case 1:
        return (
          <TechStackStep 
            uiFrameworks={uiFrameworks} 
            baseComponents={baseComponents}
            onUIFrameworkChange={handleUIFrameworkChange}
          />
        );
      case 2:
        return <ComponentsSelectionStep form={form} baseComponents={baseComponents} />;
      case 3:
        return (
          <ProjectArchitectureStep 
            form={form}
            onArchitectureChange={handleArchitectureChange}
          />
        );
      case 4:
        return <ComponentGenerationStep form={form} />;
      case 5:
        return <AdvancedSettingsStep form={form} />;
      default:
        return null;
    }
  };

  // 表单的默认初始值
  const formInitialValues = useMemo(() => {
    const defaults = {
      language: 'typescript',
      buildTool: 'vite',
      targetPlatform: 'web',
      enableAIRecommendation: true,
      maxLevels: 2,
      baseComponents: [],
      extendedComponents: [],
      generatedComponents: [],
    };
    // 合并默认值和从 Redux 加载的配置
    return { ...defaults, ...config };
  }, [config]);

  // 表单布局配置
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 6 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
  
  const tailFormItemLayout = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 24, offset: 0 },
    },
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl mx-auto">
        <Card 
          title={<Title level={2}>AI前端项目生成系统</Title>}
          variant="outlined"
          className="shadow-lg rounded-xl overflow-hidden"
        >
          <Paragraph>
            欢迎使用AI前端项目生成系统！请按步骤配置您的新项目，然后我们将为您一键生成完整的项目骨架。
          </Paragraph>
          
          <StatusAlerts items={statusAlerts} />
          
          {/* 步骤导航 */}
          <Steps current={currentStep} className="mb-8">
            {steps.map((step, index) => (
              <Step key={index} title={step.title} description={step.description} />
            ))}
          </Steps>
          
          <Spin spinning={reduxLoading}>
            <Form
              {...formItemLayout}
              form={form}
              layout="horizontal"
              initialValues={formInitialValues}
              className="mt-4"
            >
              {/* 当前步骤内容 */}
              <div className="min-h-[400px]">
                {renderStepContent()}
              </div>
              
              {/* 操作按钮 */}
              <Form.Item {...tailFormItemLayout} className="mt-8">
                <StepNavigation
                  currentStep={currentStep}
                  totalSteps={steps.length}
                  onNext={handleNext}
                  onPrev={handlePrev}
                  onSubmit={handleSubmit}
                  onReset={handleReset}
                  loading={reduxLoading}
                  apiLoading={apiLoading}
                />
              </Form.Item>

              {generatedProjectName && (
                <div className="mt-4 flex items-center gap-3">
                  <Text type="secondary">
                    项目已生成：{generatedProjectName}
                  </Text>
                  <Button type="primary" onClick={handleDownloadProject} loading={downloadLoading}>
                    下载 ZIP
                  </Button>
                </div>
              )}
            </Form>
          </Spin>
        </Card>
        
        <div className="mt-8 text-center text-gray-500">
          <Text>第{currentStep + 1}步 - {steps[currentStep]?.title}</Text>
        </div>
      </div>
    </div>
  );
};

export default ProjectConfig;
